package com.github.binarylei.curator.cluster;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @author: leigang
 * @version: 2018-04-06
 */
public class Test {

    private static final String CONNECT_ADDR = "127.0.0.1:2181";
    private static final int SEESION_OUTTIME = 5 * 1000;
    
    @org.junit.Test
    public void test() throws Exception {
        //1. 重试策略：初试时间为1s，重试10次
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 10);

        //2. 通过工厂创建连接
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_ADDR)
                .sessionTimeoutMs(SEESION_OUTTIME)
                .retryPolicy(retryPolicy)
                .build();

        //3. 开启连接
        cf.start();

        cf.create().creatingParentsIfNeeded().forPath("/cluster/c1", "c1".getBytes());
        cf.create().creatingParentsIfNeeded().forPath("/cluster/c2", "c2".getBytes());

        Thread.sleep(1000);
        cf.setData().forPath("/cluster/c1", "c1-update".getBytes());

        cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/cluster/c1");
        cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/cluster/c2");

        cf.close();
    }
}
